package com.xjscrm.server.service.friendreq.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.OperatePlan;
import com.xjscrm.common.entity.OperatePlanDevice;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.vo.newcustmoerplan.NewCustomerPlanRule;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.common.util.SleepTimeTools;
import com.xjscrm.server.dto.operateplandevice.OperatePlanDeviceQuery;
import com.xjscrm.server.mapper.OperatePlanDeviceMapper;
import com.xjscrm.server.mapper.OperatePlanMapper;
import com.xjscrm.server.service.friendreq.OperatePlanDeviceSyncService;
import com.xjscrm.server.service.friendreq.WwFriendReqService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 企业微信好友申请实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class OperatePlanDeviceSyncServiceImpl implements OperatePlanDeviceSyncService {

    @Autowired
    private OperatePlanDeviceMapper operatePlanDeviceMapper;
    @Autowired
    private OperatePlanMapper operatePlanMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwFriendReqService wwFriendReqService;

    /**
     * 处理发送好友请求任务
     *
     * @param merId
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForFriendReq")
    @TraceGenerate //注入消息id标签
    public void autoHanderWwFriendReq(@MerId Long merId) {
        //限流key
        String taskLimitKey = "-autoHanderWwFriendReq-taskLimitKey-merId=" + merId;
        Object object = redisTemplate.opsForValue().get(taskLimitKey);
        if (object == null) {
            //保存限流key
            redisTemplate.opsForValue().set(taskLimitKey, taskLimitKey, 300, TimeUnit.SECONDS);
        } else {
            return;
        }

        log.info("--进入处理发送好友请求任务--");

        try {
            //查询当前所有开启的自动发圈的配置方案
            int now = DateUtil.getTime();

            OperatePlanDeviceQuery operatePlanDeviceQuery = new OperatePlanDeviceQuery();
            operatePlanDeviceQuery.setMerId(merId);
            //方案类型(0-接受新客，1-新客运营)
            operatePlanDeviceQuery.setPlanType(0); //接受新客

            //查询所有的自动发圈配置记录
            Page<OperatePlanDevice> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<OperatePlanDevice> operatePlanDeviceList = operatePlanDeviceMapper.findByList(page, operatePlanDeviceQuery);
            while (operatePlanDeviceList != null && operatePlanDeviceList.size() > 0) {
                for (OperatePlanDevice operatePlanDevice : operatePlanDeviceList) {
                    if (operatePlanDevice.getId().longValue() >idStart.longValue()) {
                        idStart = operatePlanDevice.getId();
                    }

                    //限流判断
                    String rateLimitKey = "autoHanderWwFriendReq-taskId=" + operatePlanDevice.getId();
                    Object rateLimitKeyObject = redisTemplate.opsForValue().get(rateLimitKey);
                    if (rateLimitKeyObject == null) {
                        //保存限流key
                        redisTemplate.opsForValue().set(rateLimitKey, rateLimitKey, 300, TimeUnit.SECONDS);
                    } else {
                        continue;
                    }

                    try {

                        //查询该机器人对于的接受新客户配置方案
                        OperatePlan operatePlan = operatePlanMapper.queryById(operatePlanDevice.getPlanId());
                        if(operatePlan == null){
                            return;
                        }

                        //限制是否休眠
                        NewCustomerPlanRule newCustomerPlanRule = JSONObject.parseObject(operatePlan.getPlanRule(), NewCustomerPlanRule.class);
                        boolean sleepFlag = SleepTimeTools.verifyFriendReqSleepTime(newCustomerPlanRule);
                        if (!sleepFlag) {
                            wwFriendReqService.autoSendWwFriendReq(merId, operatePlanDevice, operatePlan);
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    } finally {
                        //保存成功之后，手动删除限流redisKey
                        redisTemplate.delete(rateLimitKey);
                    }
                }

                operatePlanDeviceQuery.setIdStart(idStart);
                operatePlanDeviceList = operatePlanDeviceMapper.findByList(page, operatePlanDeviceQuery);
            }
        } catch (Exception e) {
            log.info(e.getMessage(), e);
        } finally {
            //删除限流key
            redisTemplate.delete(taskLimitKey);
        }

    }

}
